package com.ruoyi.project.platform.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.exception.Exceptions;
import com.ruoyi.common.exception.MyAssert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.platform.domain.RRobot;
import com.ruoyi.project.platform.domain.RRobotRunning;
import com.ruoyi.project.platform.domain.StyParameter;
import com.ruoyi.project.platform.dto.RRunningMappingDto;
import com.ruoyi.project.platform.dto.UserRunningDto;
import com.ruoyi.project.platform.mapper.StyParameterMapper;
import com.ruoyi.project.platform.service.IRRobotRunningService;
import com.ruoyi.project.platform.service.IRRobotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.platform.mapper.RRunningMappingMapper;
import com.ruoyi.project.platform.domain.RRunningMapping;
import com.ruoyi.project.platform.service.IRRunningMappingService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 运行机器人参数Service业务层处理
 *
 * @author ruoyi
 * @date 2020-07-26
 */
@Slf4j
@Service
public class RRunningMappingServiceImpl implements IRRunningMappingService {
    @Autowired
    private RRunningMappingMapper rRunningMappingMapper;

    @Autowired
    IRRobotRunningService irRobotRunningService;
    @Autowired
    private StyParameterMapper styParameterMapper;

    /**
     * 查询运行机器人参数
     *
     * @param runningId 运行机器人参数ID
     * @return 运行机器人参数
     */
    @Override
    public RRunningMapping selectRRunningMappingById(Long runningId) {
        return rRunningMappingMapper.selectRRunningMappingById(runningId);
    }

    /**
     * 查询运行机器人参数列表
     *
     * @param rRunningMapping 运行机器人参数
     * @return 运行机器人参数
     */
    @Override
    public List<RRunningMappingDto> selectRRunningMappingList(RRunningMapping rRunningMapping) {
        return rRunningMappingMapper.selectRRunningMappingDtoList(rRunningMapping);
    }

    /**
     * 新增运行机器人参数
     *
     * @param rRunningMapping 运行机器人参数
     * @return 结果
     */
    @Override
    public int insertRRunningMapping(RRunningMapping rRunningMapping) {
        return rRunningMappingMapper.insertRRunningMapping(rRunningMapping);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveRRunningMappingList(List<RRunningMappingDto> rRunningMapping, Long runningId) {
        if (!rRunningMapping.isEmpty()) rRunningMapping.forEach(m -> {
            RRunningMapping rm = new RRunningMapping();
            rm.setRunningId(m.getRunningId());
            rm.setParameterId(m.getParameterId());
            rm.setParameterValue(m.getParameterValue());
            if (rm.getRunningId() == null) {
                rm.setRunningId(runningId);
                this.insertRRunningMapping(rm);
                RRobotRunning rRobot = new RRobotRunning();
                rRobot.setRunningId(runningId);
                rRobot.setRunningStatus(2);
                irRobotRunningService.updateRRobotRunning(rRobot);
            } else {
                StyParameter sp = styParameterMapper.selectStyParameterById(rm.getParameterId());
                if (sp == null)
                    rRunningMappingMapper.deleteRRunningMappingByUniId(rm.getRunningId(), rm.getParameterId());
                else
                    this.updateRRunningMapping(rm);
            }
        });

        return rRunningMapping.size();
    }


    /**
     * 修改运行机器人参数
     *
     * @param rRunningMapping 运行机器人参数
     * @return 结果
     */
    @Override
    public int updateRRunningMapping(RRunningMapping rRunningMapping) {
        return rRunningMappingMapper.updateRRunningMapping(rRunningMapping);
    }

    /**
     * 批量删除运行机器人参数
     *
     * @param runningIds 需要删除的运行机器人参数ID
     * @return 结果
     */
    @Override
    public int deleteRRunningMappingByIds(Long[] runningIds) {
        return rRunningMappingMapper.deleteRRunningMappingByIds(runningIds);
    }

    /**
     * 删除运行机器人参数信息
     *
     * @param runningId 运行机器人参数ID
     * @return 结果
     */
    @Override
    public int deleteRRunningMappingById(Long runningId) {
        return rRunningMappingMapper.deleteRRunningMappingById(runningId);
    }

    @Override
    public int updateOrSaveRRunningMapping(Map<String, String> mappings) {
        log.info("update or save mapping {}", JSON.toJSONString(mappings));
        String strategyId = mappings.get("strategyId");
        String runningId = mappings.get("runningId");
        MyAssert.assertNotEmpty(strategyId, Exceptions.BAD_STRATEGY_ID);
        MyAssert.assertNotEmpty(runningId, Exceptions.BAD_RUNNING_ID);

        StyParameter parameterQuery = new StyParameter();
        parameterQuery.setStrategyId(Long.parseLong(strategyId));
        List<StyParameter> styParameters = styParameterMapper.selectStyParameterList(parameterQuery);

        mappings.forEach((k, v) -> {
            if (!k.equals("strategyId") && !k.equals("runningId")) {
                RRunningMapping ss = new RRunningMapping();
                ss.setRunningId(Long.parseLong(runningId));

                Boolean matched = false;

                for (StyParameter param : styParameters) {
                    if (param.getName().equals(k)) {
                        ss.setParameterId(param.getParameterId());
                        if (StringUtils.isEmpty(v)) {
                            ss.setParameterValue(param.getDefaultValue());
                        } else if (v.equals("${ST}")) {
                            ss.setParameterValue(System.currentTimeMillis() + "");
                        } else {
                            ss.setParameterValue(v);
                        }

                        matched = true;
                    }
                }

                if (!matched) {
                    log.info("parameter not found {}", k);
                }else {

                    RRunningMapping mappingQuery = new RRunningMapping();
                    mappingQuery.setRunningId(ss.getRunningId());
                    mappingQuery.setParameterId(ss.getParameterId());
                    List<RRunningMapping> mappingResults = rRunningMappingMapper.selectRRunningMappingList(mappingQuery);
                    if(mappingResults.isEmpty()){
                        rRunningMappingMapper.insertRRunningMapping(ss);
                    }else {
                        rRunningMappingMapper.updateRRunningMapping(ss);
                    }
                }

            }
        });


        return mappings.size();
    }
}
